package cn.com.eado.crm.v.fragment


import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.com.eado.crm.R
import cn.com.eado.crm.app.*
import cn.com.eado.crm.app.utils.SpUtil
import cn.com.eado.crm.databinding.FragmentHomeBinding
import cn.com.eado.crm.m.db.AppIcon
import cn.com.eado.crm.m.db.MyDatabase
import cn.com.eado.crm.v.adapter.RVIconAdapter
import cn.com.eado.preado.app.utils.autoCleared
import cn.com.eado.preado.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.fragment_home.*
import kotlin.concurrent.thread

/**
 * A simple [Fragment] subclass.
 */
class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(R.layout.fragment_home) {

    private var vm by autoCleared<LoginViewModel>()
    private var adapter by autoCleared<RVIconAdapter>()
    private val mList: MutableList<AppIcon> = mutableListOf()
    private val deleteList: MutableList<AppIcon> = mutableListOf()

    override fun onResume() {
        super.onResume()
        initUserIcon()
    }

    override fun initTheFragment() {
        initView()
    }

    private fun initView() {
        tvName.text = SpUtil.readString(MyApp.instance, KEY_USER_NAME, "unknown")
        ivApp.setOnClickListener { Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_appFragment) }
        btDone.setOnClickListener { updateIcon() }
        initRecyclerView()
    }

    private fun updateIcon() {
        thread {
            MyDatabase.getInstance().appIconDao().delete(deleteList)
            activity?.runOnUiThread {
                shoeDelete()
            }
        }
    }

    private fun initRecyclerView() {
        recyclerView.layoutManager = GridLayoutManager(activity, 4) as RecyclerView.LayoutManager?
        val adapter = RVIconAdapter(
            { view, pos, bean ->  //click
                if(bean.delete){
                    deleteList.add(bean)
                    mList.removeAt(pos)
                    this.adapter.refresh(mList)
                }else{
                    gotoFragment(bean)
                }
            },
            { pos, bean ->  //long click
                shoeDelete()
            })
        recyclerView.adapter = adapter
        this.adapter = adapter
    }

    private fun shoeDelete(){
        for(i in 0 until mList.size) {
            mList[i].delete = !mList[i].delete
        }
        this.adapter.refresh(mList)
        showDone(mList[0].delete)
    }

    private fun showDone(show: Boolean){
        if (show){
            layoutDone.visibility = View.VISIBLE
            layoutDone.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fade_in_top))
            deleteList.clear()
        }else{
            layoutDone.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fade_out_top))
            layoutDone.visibility = View.GONE
        }
    }

    private fun initUserIcon(){
        Log.e("tag", "initUserIcon")
        thread {
            val userName = SpUtil.readString(MyApp.instance, KEY_USER_NAME, "unknown")
            val userId = SpUtil.readInt(MyApp.instance, KEY_USER_ID, 0)
            val account = MyDatabase.getInstance().accountDao().queryWithName(userName)
            if (account?.login == false){//不同用户第一次登录时显示的图标
                account.login = true
                MyDatabase.getInstance().accountDao().update(account)
                val temp = listOf<AppIcon>(
                    AppIcon(0, userId, "企业信息管理", R.drawable.ic_dashboard_black_24dp, true, false),
                    AppIcon(0, userId, "设计院信息管理", R.drawable.ic_dashboard_black_24dp, true, false),
                    AppIcon(0, userId, "项目挖掘", R.drawable.ic_dashboard_black_24dp, true, false),
                    AppIcon(0, userId, "个人报备", R.drawable.ic_dashboard_black_24dp, true, false)
                )
                MyDatabase.getInstance().appIconDao().insertAll(temp)
            }
            val list = MyDatabase.getInstance().appIconDao().queryShow(true, userId)  //用户原有的list
            mList.clear()
            if (list?.isNotEmpty() == true){
                Log.e("tag", "resId=${list[0].resId}")  //2131165288
                mList.addAll(list)
            }
            activity?.runOnUiThread { this.adapter.refresh(mList) }
        }
    }


    private fun gotoFragment(icon: AppIcon){
        val bundle = Bundle()
        bundle.putString("name", icon.name)
        when(icon.name){
            "企业信息管理" -> {
                Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_companyFragment, bundle)
            }
            "设计院信息管理" -> {
                Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_instituteFragment, bundle)
            }
            "项目挖掘" -> {
                Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_unearchFragment, bundle)
            }
            "个人报备" -> {
                Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_personBaoBeiFragment, bundle)
            }
            "请路会杂" -> {
                Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_QLHZFragment, bundle)
            }
            "个人周报" -> {
                Navigation.findNavController(view!!).navigate(R.id.action_homeFragment_to_weeklyFragment, bundle)
            }
        }
    }

}
